<template>
	<view class="common-bg">
		<view class="pad-20">
			<uni-nav-bar :statusBar="true" :border="false" left-icon="back" background-color="transparent"
				@clickLeft="clickLeft" :title="$t('deviceSetting.deviceSetting')">
			</uni-nav-bar>
			<view class="m-t-40">
				<view class="font-11 col-000-4">
					<!-- 设备名称 -->
					{{ $t('deviceSetting.deviceName') }}
				</view>
				<view class="device-box m-t-8" @click="doEditDeviceName">
					<view class="ico">
						<image class="w-100" src="/static/svg/devices.svg" mode="widthFix"></image>
					</view>
					<view class="status font-18 col-000-8 font-600">
					  <span class="dot" :class="{'no': deviceDetail.device_status == 0}"></span>
					  {{deviceDetail.device_name}}
					</view>
					<view class="edit-icon">
						<uni-icons type="compose" size="20" color="rgba(0,0,0,0.4)"></uni-icons>
					</view>
				</view>
			</view>
			<view class="section-box">
				<view class="item shadow" @click="doShare()">
					<view class="left">
						<view class="ico">
							<image style="width: 56rpx;height: 56rpx" class="w-100" src="/static/images/share.png" mode="widthFix"></image>
						</view>
						<view class="font-16 col-000-8 font-500">
							<!-- 设备共享 -->
							{{ $t('deviceSetting.deviceShare') }}
						</view>
					</view>
					<view class="right">
						<uni-icons color="rgba(0,0,0,0.8)" type="forward" size="26"></uni-icons>
					</view>
				</view>
				<view class="item shadow">
					<view class="left">
						<view class="ico">
							<image style="width: 56rpx;height: 56rpx" class="w-100" src="/static/images/help.png" mode="widthFix"></image>
						</view>
						<view class="font-16 col-000-8 font-500">
							<!-- 帮助 -->
							{{ $t('deviceSetting.help') }}
						</view>
					</view>
					<view class="right">
						<uni-icons color="rgba(0,0,0,0.8)" type="forward" size="26"></uni-icons>
					</view>
				</view>
				<view class="item shadow" @click="doJz">
					<view class="left">
						<view class="ico">
							<image style="width: 56rpx;height: 56rpx" class="w-100" src="/static/images/jz.png" mode="widthFix"></image>
						</view>
						<view class="font-16 col-000-8 font-500">
							<!-- 校准 -->
							{{ $t('deviceSetting.calibration') }}
						</view>
					</view>
					<view class="right">
						<uni-icons color="rgba(0,0,0,0.8)" type="forward" size="26"></uni-icons>
					</view>
				</view>
				<view class="item shadow">
					<view class="left">
						<view class="ico">
							<image style="width: 56rpx;height: 56rpx" class="w-100" src="/static/images/update.png" mode="widthFix"></image>
						</view>
						<view class="font-16 col-000-8 font-500">
							<!-- 固件升级 -->
							{{ $t('deviceSetting.firmwareUpgrade') }}
						</view>
						<view class="font-11 col-000-4" style="margin-left: 32rpx;">
							<!-- 当前版本 -->
							{{ $t('deviceSetting.currentVersion') }}：v1.0.0
						</view>
					</view>
					<view class="right">
						<uni-icons color="rgba(0,0,0,0.8)" type="forward" size="26"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<view class="btn-zan"></view>
		<view class="btn-foot flex-center-center" @click="doDelete">
			<image style="width: 56rpx;height: 56rpx" class="w-100" src="/static/images/clear.png" mode="widthFix"></image>
			<view class="">
				<!-- 移除设备 -->
				{{ $t('deviceSetting.removeDevice') }}
			</view>
		</view>
		<!-- 移除设备弹窗 -->

		<confirmPopup :title="$t('deviceSetting.removeDevice')" :content="$t('deviceSetting.removeDeviceTip')" :confirmText="$t('deviceSetting.removeDevice')" ref="ref_confirm_delete" @cancel="canelDelete" @confirm="confirmDelete" />
		<!-- 校准弹窗 -->

		<confirmPopup :title="$t('deviceSetting.calibration')" :content="$t('deviceSetting.calibrationTip')" :cancelText="$t('deviceSetting.cancel')" :confirmText="$t('deviceSetting.calibration')" ref="ref_confirm_jz" @cancel="canelJz" @confirm="confirmJz" />
		
		<!-- 修改设备名称弹窗 -->
		<uni-popup ref="ref_edit_name" type="center">
			<view class="edit-name-popup">
				<view class="popup-title">{{ $t('deviceSetting.editDeviceName') }}</view>
				<view class="popup-content">
					<input 
						class="device-name-input" 
						v-model="editDeviceName" 
						:placeholder="$t('deviceSetting.deviceNamePlaceholder')" 
						:maxlength="20"
						@input="onDeviceNameInput"
					/>
					<view class="char-count">{{ deviceNameLength }}/20</view>
				</view>
				<view class="popup-footer">
					<view class="btn-cancel" @click="cancelEditName">{{ $t('deviceSetting.cancel') }}</view>
					<view class="btn-confirm" @click="confirmEditName">{{ $t('deviceSetting.save') }}</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import confirmPopup from '@/components/diy-popup/index.vue'
  import deviceApi from '@/api/device.js';
  import deviceStore from '@/store/deviceStore.js';
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		data() {
			return {
				status: 1,
        deviceSn: '',
        deviceDetail: {
					device_id: '',
					device_name: '',
					sn: '',
					device_status: 0,
					owner_id: ''  // 添加 owner_id 字段
				},
				editDeviceName: '',
				deviceNameLength: 0,
			}
		},
		components: {
			confirmPopup
		},
		onLoad(option) {
			const sn = option?.sn || '';
      this.deviceSn = sn;
			if(!sn) {
				uni.showToast({
					title: this.$t('list.device_not_exist'),
					icon: 'none'
				})
				return
			}
			
			console.log(`[DEVICE-SETTING] 使用传递的设备SN: ${this.deviceSn}`);
      this.getDetailBySn(sn);
		},

		created() {
			// created 钩子中不再获取参数
		},
		methods: {
      //通过SN获取设备详情
      async getDetailBySn(sn) {
        try {
          // 从数据库获取设备详情
          const res = await deviceApi.getDeviceDetail({ sn });
          if (res.errCode === 0 && res.data) {
            this.deviceDetail = {
              device_id: res.data.id, // API返回的id字段就是设备的_id
              device_name: res.data.device_name || `设备 ${sn}`,
              sn: sn,
              device_status: res.data.device_status || 0,
              owner_id: res.data.owner_id  // 保存 owner_id
            };
            
            // 同步更新 deviceStore,确保后续从 store 中能获取到完整信息
            const deviceStatus = deviceStore.getDeviceStatus(sn) || {};
            deviceStore.updateDeviceStatus(sn, {
              ...deviceStatus,
              device_id: res.data.id,
              device_name: res.data.device_name,
              online: res.data.device_status === 1,
              owner_id: res.data.owner_id  // 保存 owner_id 字段
            });
            
            console.log(`[DEVICE-SETTING] 已更新设备 ${sn} 的 owner_id 信息:`, res.data.owner_id);
          } else {
            // API调用失败，尝试从缓存获取
            const deviceStatus = deviceStore.getDeviceStatus(sn);
            this.deviceDetail = {
              device_id: deviceStatus?.device_id,
              device_name: deviceStatus?.device_name || `设备 ${sn}`,
              sn: sn,
              device_status: deviceStatus?.online ? 1 : 0
            };
          }
        } catch (error) {
          console.error('[DEVICE-SETTING] 获取设备详情失败:', error);
          // 出错时从缓存获取
          const deviceStatus = deviceStore.getDeviceStatus(sn);
          this.deviceDetail = {
            device_id: deviceStatus?.device_id,
            device_name: deviceStatus?.device_name || `设备 ${sn}`,
            sn: sn,
            device_status: deviceStatus?.online ? 1 : 0
          };
        }
      },
			doShare() {
				uni.navigateTo({
					url: '/pages/device/device-share?sn=' + this.deviceSn
				})
			},
			clickLeft() {
				uni.navigateBack()
			},
			doDelete() {
				this.$refs.ref_confirm_delete.open()
			},
			canelDelete() {
				this.$refs.ref_confirm_delete.closePopup()
			},
		async confirmDelete() {
			try {
				// 显示加载提示
				uni.showLoading({
					title: this.$t('deviceSetting.removing'),
					mask: true
				});
				
			console.log('[DEVICE-SETTING] 移除设备:', this.deviceSn);
			
			let res;
			// 检查用户是设备拥有者还是分享者
			const currentUserId = store.userInfo?._id;
			const ownerId = this.deviceDetail.owner_id;  // 从 deviceDetail 中获取
			
			console.log('[DEVICE-SETTING] owner_id 字段值:', ownerId);
			console.log('[DEVICE-SETTING] 当前用户ID:', currentUserId);
			
			// 通过对比 owner_id 和当前用户 ID 判断是否是拥有者
			const isOwner = ownerId === currentUserId;
			console.log('[DEVICE-SETTING] 判断结果 - isOwner:', isOwner);
			
			if (isOwner) {
				// 拥有者：删除设备
				console.log('[DEVICE-SETTING] 用户是拥有者，删除设备');
				res = await deviceApi.deleteDeviceBySn({ sn: this.deviceSn });
			} else {
				// 分享者：移除分享关系
				console.log('[DEVICE-SETTING] 用户是分享者，移除分享关系');
				res = await deviceApi.removeDeviceShare({ sn: this.deviceSn });
			}				uni.hideLoading();
				
				if (res.errCode === 0) {
					// 关闭弹窗
					this.$refs.ref_confirm_delete.closePopup();
					
					// 从 deviceStore 中移除设备状态
					if (deviceStore.removeDevice) {
						deviceStore.removeDevice(this.deviceSn);
					}
					
					// 立即跳转，避免 deviceStatusMixin 继续访问已删除的设备
					uni.reLaunch({
						url: '/pages/device/device'
					});
					
					// 在跳转后显示成功提示
					setTimeout(() => {
						uni.showToast({
							title: this.$t('deviceSetting.removeSuccess'),
							icon: 'success',
							duration: 1500
						});
					}, 100);
				} else {
					throw new Error(res.errMsg || '移除失败');
				}
			} catch (error) {
				console.error('[DEVICE-SETTING] 移除设备失败:', error);
				uni.hideLoading();
				
				// 显示错误提示
				uni.showToast({
					title: error.message || this.$t('deviceSetting.removeFailed'),
					icon: 'none',
					duration: 3000
				});
			}
		},
		doJz() {
				this.$refs.ref_confirm_jz.open()
			},
			canelJz() {
				this.$refs.ref_confirm_jz.closePopup()
			},
			confirmJz() {
				
			},
			// 打开修改设备名称弹窗
			doEditDeviceName() {
				this.editDeviceName = this.deviceDetail.device_name;
				this.deviceNameLength = this.getChineseLength(this.editDeviceName);
				this.$refs.ref_edit_name.open();
			},
			// 取消修改设备名称
			cancelEditName() {
				this.$refs.ref_edit_name.close();
			},
			// 计算中文字符长度（中文算1个字符）
			getChineseLength(str) {
				if (!str) return 0;
				return str.length;
			},
			// 输入设备名称时更新字符计数
			onDeviceNameInput(e) {
				const value = e.detail.value;
				this.deviceNameLength = this.getChineseLength(value);
			},
			// 确认修改设备名称
			async confirmEditName() {
				const newName = this.editDeviceName.trim();
				
				if (!newName) {
					uni.showToast({
						title: this.$t('deviceSetting.deviceNameRequired'),
						icon: 'none'
					});
					return;
				}
				
				if (this.getChineseLength(newName) > 20) {
					uni.showToast({
						title: this.$t('deviceSetting.deviceNameTooLong'),
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.showLoading({
						title: this.$t('deviceSetting.saving'),
						mask: true
					});
					
					// 从 deviceStore 获取设备状态（包含 device_id）
					const deviceStatus = deviceStore.getDeviceStatus(this.deviceSn);
					let deviceId = deviceStatus?.device_id || this.deviceDetail.device_id;
					
					// 如果还是没有device_id，先获取设备详情
					if (!deviceId) {
						const detailRes = await deviceApi.getDeviceDetail({ sn: this.deviceSn });
						if (detailRes.errCode === 0 && detailRes.data) {
							deviceId = detailRes.data.id;
							// 更新到 store
							deviceStore.updateDeviceStatus(this.deviceSn, {
								...deviceStatus,
								device_id: deviceId
							});
						} else {
							throw new Error('无法获取设备ID');
						}
					}
					
					// 调用API更新设备名称
					const res = await deviceApi.updateDevice({
						deviceId: deviceId,
						deviceInfo: {
							device_name: newName
						}
					});
					
					uni.hideLoading();
					
					if (res.errCode === 0) {
						// 更新本地显示
						this.deviceDetail.device_name = newName;
						
						// 更新deviceStore中的设备名称
						deviceStore.updateDeviceStatus(this.deviceSn, {
							...deviceStatus,
							device_id: deviceId,
							device_name: newName
						});
						
						uni.showToast({
							title: this.$t('deviceSetting.saveSuccess'),
							icon: 'success'
						});
						
						this.$refs.ref_edit_name.close();
					} else {
						throw new Error(res.errMsg || '保存失败');
					}
				} catch (error) {
					console.error('[DEVICE-SETTING] 修改设备名称失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: error.message || this.$t('deviceSetting.saveFailed'),
						icon: 'none'
					});
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.common-bg {
		overflow-x: hidden;
	}
	
	.btn-zan {
		width: 100%;
		height: 144rpx
	}
	.btn-foot {
		height: 100rpx;
		border-radius: 16rpx;
		border: 2rpx solid rgba(0,0,0,0.8);
		background-color: #fff;
		position: fixed;
		left: 40rpx;
		right: 40rpx;
		bottom: 44rpx;
		max-width: calc(100vw - 80rpx);
		box-sizing: border-box;
		.ico {
			width: 40rpx;
			height: 40rpx;
			margin-right: 16rpx;
		}
	}
	.section-box {
		width: 100%;
		margin-top: 72rpx;
		.item {
			width: 100%;
			margin-bottom: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx 32rpx;
			.left {
				display: flex;
				align-items: center;
				justify-content: flex-start;
			}
			.ico {
				width: 56rpx;
				height: 56rpx;
				margin-right: 32rpx;
				opacity: 0.5;
			}
		}
	}
	.device-box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		cursor: pointer;
		position: relative;
		.ico {
			width: 64rpx;
			height: 64rpx;
		}
		.edit-icon {
			margin-left: 16rpx;
		}
	}
	
	.edit-name-popup {
		width: 600rpx;
		background-color: #fff;
		border-radius: 24rpx;
		padding: 40rpx;
		
		.popup-title {
			font-size: 32rpx;
			font-weight: 600;
			color: rgba(0,0,0,0.8);
			text-align: center;
			margin-bottom: 32rpx;
		}
		
		.popup-content {
			margin-bottom: 32rpx;
			
			.device-name-input {
				width: 100%;
				height: 88rpx;
				border: 2rpx solid rgba(0,0,0,0.1);
				border-radius: 12rpx;
				padding: 0 24rpx;
				font-size: 28rpx;
				color: rgba(0,0,0,0.8);
				box-sizing: border-box;
			}
			
			.char-count {
				text-align: right;
				font-size: 24rpx;
				color: rgba(0,0,0,0.4);
				margin-top: 8rpx;
			}
		}
		
		.popup-footer {
			display: flex;
			align-items: center;
			justify-content: space-between;
			gap: 24rpx;
			
			.btn-cancel, .btn-confirm {
				flex: 1;
				height: 88rpx;
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				font-weight: 500;
			}
			
			.btn-cancel {
				background-color: rgba(0,0,0,0.05);
				color: rgba(0,0,0,0.6);
			}
			
			.btn-confirm {
				background-color: #000;
				color: #fff;
			}
		}
	}
	.status {
	  text-align: center;
	  .dot {
	    width: 12rpx;
	    height: 12rpx;
	    border-radius: 100%;
	    margin-right: 16rpx;
			margin-left: 16rpx;
	    display: inline-block;
	    background-color: #22C55D;
			position: relative;
			top: -6rpx;
	
	    &.no {
	      background-color: rgba(0, 0, 0, 0.4);
	    }
	  }
	}
</style>